<template>
  <div v-if="userInfo">
    <h2>修改密码</h2>

    <el-form :model="form" :rules="rules" label-width="auto" style="max-width: 600px">
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input v-model="form.password" show-password />
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" show-password />
      </el-form-item>
      <el-form-item label="验证码" v-if="emailValidated" prop="code">
        <el-input v-model="form.code">
          <template #append>
            <el-button :disabled="isSending" @click="sendCode">{{ buttonText }}</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <div class="div1">
          <el-button type="primary" @click="onSubmit">确认</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>

  <el-empty v-else description="请先登录哦">
    <el-button type="primary" @click="goTo('/user/login')">去登录/注册</el-button>
  </el-empty>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import axios from 'axios';
import { FormRules } from 'element-plus';
import { useUserStore } from '@/stores/userStore';


const store = useUserStore();
const userInfo = computed(() => store.user);

const form = reactive({
  email: '',
  password: '',
  confirmPassword: '',
  code: '',

})


import { useGoTo } from '@/hooks/useGoTo';
const { goTo } = useGoTo()

const formRef = ref(null);
const emailValidated = ref(false);
const countdown = ref(0);
const isSending = ref(false);
let countdownInterval: ReturnType<typeof setInterval> | null = null;


const rules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && value.trim() !== '') {
          // 假设邮箱格式正确且不为空，则验证通过  
          emailValidated.value = true;
          callback();
        } else {
          emailValidated.value = false;
          callback(new Error('请输入有效的邮箱地址'));
        }
      },
      trigger: 'change'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: checkPassword, trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码长度为 6 位', trigger: 'blur' },
  ],
};

function checkPassword(rule: any, value: string, callback: any) {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== form.password) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
}





async function sendCode() {
  if (!isSending.value) {
    isSending.value = true;
    startCountdown();
    try {
      const params = {
        email: form.email
      }
      const response = await axios.get('/api/user/sendCode', { params });
      // 处理响应，例如导航到主页面或更新状态    
      console.log(response.data);

      if (response.data.code === '200') {
        ElMessage({
          message: '发送成功',
          type: 'success',
        })
      } else if (response.data.code === '-1') {
        ElMessage({
          message: response.data.msg,
          type: 'error',
        })
      }

    } catch (error) {
      // 处理错误，例如显示错误消息给用户    
      console.error(error);
      // 可以使用 alert 或其他 UI 库来显示错误消息  
    }
  }
}


const startCountdown = () => {
  countdown.value = 60;
  countdownInterval = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(countdownInterval!);
      countdownInterval = null;
      isSending.value = false;
    }
  }, 1000);
};

const buttonText = computed(() => {
  return isSending.value ? `${countdown.value}秒后重发` : '发送验证码';
});


async function onSubmit() {
  try {
    const response = await axios.put('/api/user/update', {
      email: form.email,
      newPass: form.password,
      code: form.code,
    });


    ElMessage({
      message: '密码修改成功',
      type: 'success'
    });


  } catch (error) {
    // 处理错误，例如显示错误消息给用户    
    console.error(error);
    // 可以使用 alert 或其他 UI 库来显示错误消息  
  }
}

onUnmounted(() => {
  if (countdownInterval) {
    clearInterval(countdownInterval);
  }
});

</script>

<style scoped>
.div1 {
  width: 1200px;
  height: 70px;
  display: flex;
  justify-content: center;
  /* 水平居中 */
  align-items: center;
}
</style>